<template>
    <AppFormBuild :value="jsonData" @submit="handleSubmit" ref="appFormBuild" :allDataSource="allDataSource"
                  @addModelKey="addModelKey" :dictMap="dictMap"/>
</template>

<script>

    import AppFormBuild from "../modules/appDesigner/packages/AppFormBuild";

    export default {
        name: "BpmForm",
        components: {
            AppFormBuild,
        },
        props: {
            bpmIdType: {
                type: String,
                default: null
            },
            formId: {
                type: String,
                default: null
            },
            formCode: {
                type: String,
                default: null
            },
            startPage: {
                type: Boolean,
                default: false
            },
            editableList: {
                type: Array,
                default: () => []
            },
        },
        data() {
            return {
                id: this.formId,
                confirmLoading: false,
                url: {
                    getData: '/api/eform/engine/mobileFormEngine/getData',
                    saveData: '/api/eform/engine/mobileFormEngine/saveData'
                },
                jsonData: {},//表单模型
                jsonModel: [],//需要保存的key的集合
                jsonFieldType: {},//处理特殊字段
                allDataSource: {},//所有初始化数据
                data: {},//原始data
                dictMap: {},
                isFlow: true,
                processDefId: null,
                func: null,
            }
        },
        methods: {
            add() {
                this.open(this.url.getData + "?formKey=" + this.formCode);
            },
            detail() {
                this.open(this.url.getData + "?formKey=" + this.formCode + "&id=" + this.id);
            },
            open(url) {
                this.$mask.open();
                this.$http.get(url, undefined).then((res) => {
                    if (res.success) {
                        this.dictMap = res.result.dictModelMap;
                        this.data = res.result.data;
                        this.findAllTableData(this.data, 0);
                        this.jsonData = JSON.parse(res.result.html);
                    } else {
                        this.$notify({type: 'warning', message: res.message});
                    }
                }).catch(() => {
                    this.$notify({type: 'warning', message: '请求发生错误'});
                }).finally(() => {
                    this.$mask.close();
                });
            },
            save(func, processDefId) {
                this.func = func;
                this.processDefId = processDefId;
                this.$refs.appFormBuild.getData();
            },
            findAllTableData(data, isMain, tableName) {
                //将所有数据封装进一个对象中
                Object.keys(data).forEach(key => {
                    const value = data[key];
                    if (value instanceof Object && value.constructor == Object) {
                        //子对象，循环调用
                        this.findAllTableData(value, isMain + 1, key);
                    } else if (value instanceof Object && value.constructor == Array) {
                        //子表
                        this.allDataSource[key] = value;
                    } else {
                        if (isMain == 1) {
                            this.allDataSource[key] = value;
                        } else {
                            this.allDataSource[tableName + '-' + key] = value;
                        }
                    }
                });
            },
            //data是原始数据，用来查找对象关型，allData是表单数据，用来保存的实际数据
            createBoData(data, allData, isMain, tableName) {
                const result = new Object();
                Object.keys(data).forEach(key => {
                    const value = data[key];
                    if (value instanceof Object && value.constructor == Object) {
                        //子对象，循环调用
                        result[key] = this.createBoData(value, allData, isMain + 1, key) || {};
                    } else if (value instanceof Object && value.constructor == Array) {
                        //子表
                        result[key] = allData[key] || [];
                    } else if (key == 'id' && value) {
                        result[key] = value;
                    } else {
                        let modelKey;
                        if (isMain == 1) {
                            modelKey = key;
                        } else {
                            modelKey = tableName + '-' + key;
                        }
                        if (this.jsonModel.indexOf(modelKey) != -1 && allData.hasOwnProperty(key)) {
                            //处理复选框
                            if (this.jsonFieldType[modelKey] === 'checkbox') {
                                result[key] = allData[key].join(",");
                            } else {
                                result[key] = allData[key];
                            }
                        }
                    }
                });
                return result;
            },
            addModelKey(modelKey, fieldType) {
                this.jsonModel.push(modelKey);
                this.jsonFieldType[modelKey] = fieldType;
            },
            handleSubmit(values) {
                let httpurl = this.url.saveData + '?formKey=' + this.formCode;
                if (this.processDefId) {
                    httpurl += "&processDefId=" + this.processDefId;
                }
                httpurl += "&isFlow=" + this.isFlow;

                const formData = this.createBoData(this.data, values, 0);

                const boKey = Object.keys(formData)[0];

                if (this.id) {
                    formData[boKey].id = this.id;
                }
                this.$mask.open();
                this.$http.post(httpurl, {formData: formData}).then((res) => {
                    if (res.success) {
                        this.$notify({type: 'success', message: res.message});
                        if (!this.id) {
                            this.id = res.result;
                        }
                        if (typeof this.func === "function") {
                            this.func(this.id);
                        }
                    } else {
                        this.$notify({type: 'warning', message: res.message});
                    }
                }).catch(() => {
                    this.$notify({type: 'warning', message: '请求发生错误'});
                }).finally(() => {
                    this.$mask.close();
                });
            },
            editableModel(jsonList) {
                if (!jsonList) {
                    return;
                }
                jsonList.forEach(vo => {
                    if (vo.model) {
                        vo.options.disabled = !(this.editableList.indexOf(vo.model) != -1 || this.startPage);
                    } else if (vo.type == 'editableTable' && vo.tableName) {
                        vo.options.disabled = !(this.editableList.indexOf(vo.tableName) != -1 || this.startPage);
                    } else {
                        this.editableModel(vo.list);
                        this.editableModel(vo.trs);
                        this.editableModel(vo.tds);
                        this.editableModel(vo.columns);
                        this.editableModel(vo.tabs);
                    }
                });
            }
        },
        watch: {
            jsonData: {
                handler(value) {
                    this.editableModel(value.list);
                },
                immediate: true
            },
            editableList: {
                handler() {
                    this.editableModel(this.jsonData.list);
                },
                immediate: true
            }
        },
        created() {
            if (!this.formId && this.bpmIdType == "formCode" || this.bpmIdType == "processDefId") {
                this.add();
            } else {
                this.detail();
            }
        }
    }
</script>
